package com.alpha.components;

import com.alpha.common.utils.BusinessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * redis缓存工具
 * @author zhaojiulin
 * @time 2020/2/26 10:40
 */
@Component
public class RedisService {

    private final StringRedisTemplate stringRedisTemplate;
    private final RedisTemplate<String, Object> redisTemplate;

    public RedisService(StringRedisTemplate stringRedisTemplate, RedisTemplate<String, Object> redisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.redisTemplate = redisTemplate;
    }

    private static final long DEFAULT_EXPIRE = 60 * 60 * 24;

    /**
     * 存入字符串
     * @param key 键
     * @param value 值
     */
    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    /**
     * 根据key获取值
     * @param key 键
     * @return 字符串值
     */
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 设置有效期
     * @param key 键
     * @param expire 秒数
     * @return true
     */
    public boolean expire(String key, long expire) {
        return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    /**
     * 删除
     * @param key
     */
    public void remove(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 增量
     * @param key
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new BusinessException("递加因子必须大于0");
        }
        return stringRedisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     * @param key 键
     * @param delta 变量
     * @return 值
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new BusinessException("递减因子必须大于0");
        }
        return stringRedisTemplate.opsForValue().decrement(key, -delta);
    }


    public void cacheList(String key , List<?> list) {
        Object o = redisTemplate.opsForValue().get(key);
    }
}
